﻿
(function ($) {
    var _apiKey = "106b0ea6f45ac8ef35399477729afd93"; //dev
    var _secret = "d8af3a82912b0f5a"; //dev

    $.widget("msls.lightswitchFlickrControl", {
        options: {
            apiKey: _apiKey,
        },

        _create: function () {
        },

        _init: function () {
        },

        destroy: function () {
        },

        _handleError: function (error) {
            alert("An error occurred.  " + error.message);
        },

        searchPhotos: function (place) {
            if (place.Latitude != null && place.Longitude != null) {
                var widgetInstance = this;
                var perPage = '25';
                //var showOnPage = '6';
                //http://www.flickr.com/services/api/explore/flickr.photos.search
                $.getJSON('http://api.flickr.com/services/rest/?format=json&method='
                        + 'flickr.photos.search&api_key=' + widgetInstance.options.apiKey     //+ '&user_id=' + userId + '&tags=' + tag 
                        + '&per_page=' + perPage + '&accuracy=11&radius=1&radius_units=km&lat=' + place.Latitude + '&lon=' + place.Longitude
                        + '&jsoncallback=?'
                 ).done(function (data) {
                     //var classShown = 'class="lightbox"';
                     //var classHidden = 'class="lightbox hidden"';
                     if (data.photos != null) {
                         $.each(data.photos.photo, function (i, rPhoto) {
                             var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/'
                               + rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret;

                             var thumbPhotoURL = basePhotoURL + '_s.jpg';
                             var mediumPhotoURL = basePhotoURL + '.jpg';

                             var photoStringStart = '<a ';
                             var photoStringEnd = 'title="' + rPhoto.title + '" href="' +
                                 mediumPhotoURL + '"><img src="' + thumbPhotoURL + '" alt="' +
                                 rPhoto.title + '"/></a>;'
                             var photoString = photoStringStart + photoStringEnd;
                             //(i < showOnPage) ?
                             //photoStringStart + classShown + photoStringEnd :
                             //photoStringStart + classHidden + photoStringEnd;

                             $(photoString).appendTo("#FlickrImagesDiv");
                         });
                         //$("a.lightbox").lightBox();
                     }
                 }).fail(function (jqXHR, textStatus, errorThrown) {
                     alert('Could not connect to flickr API');
                 });
            }
        },
    });

}(jQuery));
